package com.example.amoocspringboot.entity;

import lombok.Getter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Collections;
import java.util.Objects;

@Getter
public class LoginUser implements UserDetails {

    // 辅助方法：获取底层用户对象
    private final User user;

    // 使用带参数的构造函数
    public LoginUser(User user) {
        Objects.requireNonNull(user, "用户对象不能为空");
        this.user = user;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 根据 isAdmin 字段确定用户角色
        String role = (user.getIsAdmin() != null && user.getIsAdmin() == 1) ? "ROLE_ADMIN" : "ROLE_USER";
        return Collections.singletonList(new SimpleGrantedAuthority(role));
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    // 账户状态管理 - 根据 status 字段实现
    @Override
    public boolean isAccountNonExpired() {
        return user.getStatus() != null && user.getStatus() == 1;
    }

    @Override
    public boolean isAccountNonLocked() {
        // 假设 status 同时控制锁定状态（1=正常，0=锁定）
        return user.getStatus() != null && user.getStatus() == 1;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        // 假设证书永不过期
        return true;
    }

    @Override
    public boolean isEnabled() {
        // 使用 status 字段启用状态（1=启用，0=禁用）
        return user.getStatus() != null && user.getStatus() == 1;
    }

}